package com.chenfan.gateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;

/**
 * @author lizhejin
 */
@Component
public class AppAuthorizeGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {

	private final Logger log = LoggerFactory.getLogger(AppAuthorizeGatewayFilterFactory.class);
	private static final String AUTHORIZATION_TOKEN = "Authorization";
	private static final String AUTHORIZATION = "userToken";
	private static final String USER_AGENT = "user_agent";

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public GatewayFilter apply(Object config) {
		return (exchange, chain) -> {
			String token = exchange.getRequest().getHeaders().getFirst(AUTHORIZATION_TOKEN);
			String agent = exchange.getRequest().getHeaders().getFirst(USER_AGENT);
			if(agent != null) {
				if(token != null && stringRedisTemplate.opsForValue().get(AUTHORIZATION+":"+token) != null) {
					return chain.filter(exchange);
				}
				log.error("验证不通过,token不存在!AppAuthorize.token="+token);
	            ServerHttpResponse response = exchange.getResponse();
	            response.setStatusCode(HttpStatus.UNAUTHORIZED);
	            return response.setComplete();
			}
			return chain.filter(exchange);
		};
	}

}
